* August 21, 2015
* This code runs the production-function estimation on the single-product firms

*Create postfile to store translog production coefficients created by 02_pf.do
*postfile tlogcoef pnic2 N tl_l_a tl_m_a tl_k_a tl_ll_a tl_mm_a tl_kk_a tl_lm_a tl_lk_a tl_mk_a tl_lmk_a tl_delta1_a tl_delta2_a tl_delta3_a tl_delta4_a tl_delta5_a tl_l_b tl_m_b tl_k_b tl_ll_b tl_mm_b tl_kk_b tl_lm_b tl_lk_b tl_mk_b tl_lmk_b tl_delta1_b tl_delta2_b tl_delta3_b tl_delta4_b tl_delta5_b using tlogcoefpost.dta,replace

use ${worklocal}/singleproduct_data, clear
	*keep the main sectors in the data.
*	keep if inlist(pnic2,15,17,18,21,24,25,26,27,28,29,31,32,34)
		
	* estimate 2-digit level. Combine sectors 17 and 18, and 31 and 32.
*		replace pnic2 = 17 if pnic2==18
*		replace pnic2 = 31 if pnic2==32

		egen sector	=	group(pnic2)
		sum sector
		global N = r(max)

		forvalues i=1/$N {
		preserve
			keep if sector==`i' 
			cap do "${code}/02a_pfalgorithm.do"
			if _rc==0 {
				keep pnic2 beta* gamma* delta* nrobs*
				duplicates drop
				save theta_`i', replace
				}
		restore
		}

*	use theta_1, clear
*	erase theta_1.dta
*	forvalues i=2/$N {
*	append using theta_`i'
*	erase theta_`i'.dta
*	}		
	local _rc=1
	local n=1
	while _rc!=0 {
		cap use theta_`n', clear
		cap erase theta_`n'.dta	
		local ++n
		}
	forvalues i=`n'/$N {	
		cap append using theta_`i'
		cap erase theta_`i'.dta
		}
	sort pnic2 
	isid pnic2
	save tmp, replace


use rootfile_temp, clear
sort pnic2
merge m:1 pnic2 using tmp
	cap erase tmp.dta
	keep if _merge==3
	drop _m

	cap drop p_j
	gen PRICE	=	sv/sq
	gen p_j		=	ln(PRICE)

	gen p_j2		= p_j^2
	bysort pnic2 UNIT2 year : egen PRICE_mean = mean(PRICE)
	gen p_jmean 	=	ln(PRICE_mean)
	bysort year pnic2 unit: egen ms_mean	= mean(msq)
	gen msdif		=	msq - ms_mean
	replace msq		=	msdif 
	gen p_ms		=	p_j*msq
*** MTB: CHANGE IN ORIGINAL CODE: TARRIFS COMMENTED OUT AND ADDITIONAL REGRESSORS ADDED
	gen wfjt		=	gamma1_1*p_j + gamma1_2*p_j2 + gamma1_3*msq + gamma1_4*p_ms + /*gamma1_5*pqt*/ gamma1_5*exp_p + gamma1_6*dest_p + delta1_7*dest_p_sq + gamma1_8*treated_p

	*purge input-prices with unit-product12-year FEs
	areg wfjt, a(up12y)
		predict wfjt_tmp,r
		drop wfjt			
		rename wfjt_tmp wfjt
		
	* create translog terms:
	gen lk		=	l*k
	gen lm		=	l*m
	gen mk		=	m*k
	gen lmk		=	l*m*k
	replace m	=	m_s
save "data_&_theta.dta", replace

